package com.wt.struggle.goodbye.user.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.DatePicker
import android.widget.TextView
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ProActivity
import com.wt.struggle.goodbye.base.Send
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.real_name_layout.*
import java.util.*

class RealNameActivity : ProActivity() {
    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            Send.UPDATE_USER_CODE -> {
                if (netInfo.code == Config.SUCCESS) {
                    finish()
                }
            }
        }
    }

    var userInfo: ProUserInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.real_name_layout)

        userInfo = intent.getParcelableExtra("userInfo")

        if (userInfo != null) {
            showUserInfo(userInfo)
        }

        tvTitle.text = "实名认证"

        tvRight.text = "保存"

        initSexSpinner()
        initGuoJiaSpinner()
        initStyleSpinner()
        initClick()

        getLocation()

    }

    private fun initClick() {
        imageBack.setOnClickListener {
            finish()
        }
        tvRight.setOnClickListener {
            save()
        }

        timeLinear.setOnClickListener {
            chooseTime()
        }
    }

    private fun showUserInfo(userInfo: ProUserInfo?) {
        etRealName.hint = userInfo!!.realName
        val card = userInfo.cardNo
        if (card != null) {
            etIdCardNumber.hint = card
        } else {
            etIdCardNumber.hint = ""
        }

        val cp = userInfo.cardPeriod
        if (cp != null) {
            tvChooseCardTime.text = cp
        } else {
            tvChooseCardTime.text = ""
        }


    }


    /**
     * 获取位置服务
     */
    private fun getLocation() {
        val code = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val code2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

        if (code == PackageManager.PERMISSION_GRANTED && code2 == PackageManager.PERMISSION_GRANTED) {

            get()

        } else {

            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
                5678
            )
        }

    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 5678) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                grantResults[1] == PackageManager.PERMISSION_GRANTED
            ) {

                get()

            }
        }
    }

    var location: Location? = null
    var addressStr: String = ""

    @SuppressLint("MissingPermission")
    fun get() {
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val locationProvider = LocationManager.NETWORK_PROVIDER
        // 获取Location
        location = locationManager.getLastKnownLocation(locationProvider)

        // 监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 5000, 1f, object : LocationListener {
            override fun onLocationChanged(p0: Location?) {
                this@RealNameActivity.location = p0

                val geocoder = Geocoder(this@RealNameActivity)

                val arr = geocoder.getFromLocation(location!!.latitude, location!!.longitude, 1);

                val address = arr[0]
                addressStr = address.featureName

            }

            override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {

            }

            override fun onProviderEnabled(p0: String?) {

            }

            override fun onProviderDisabled(p0: String?) {

            }

        })


    }


    private fun chooseTime() {
        val view = layoutInflater.inflate(R.layout.choose_date_layout, null)
        val datePicker = view.findViewById<DatePicker>(R.id.datePicker)
        val cal = Calendar.getInstance()
        cal.timeInMillis = System.currentTimeMillis()
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null)

        val builder = AlertDialog.Builder(this)
        builder.setView(view)
            .setPositiveButton("确定") { dialog, _ ->
                val timeStr = String.format(
                    "%d-%02d-%02d",
                    datePicker.year,
                    datePicker.month + 1,
                    datePicker.dayOfMonth
                )

                tvChooseCardTime.text = timeStr

                dialog.dismiss()

            }.setNegativeButton("取消") { _, _ -> }.show()
    }

    private fun initStyleSpinner() {
        cardStyleSpinner.adapter =
                ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, styleArr)
        cardStyleSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {

            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                chooseStyle = styleArr[p2]
                (p1 as TextView).textSize = 14f
                (p1 as TextView).gravity = Gravity.END
            }

        }
    }

    private fun initGuoJiaSpinner() {
        guojiSpinner.adapter =
                ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, guojiArr)
        guojiSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {
            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                chooseCountry = guojiArr[p2]
                (p1 as TextView).textSize = 14f
                (p1 as TextView).gravity = Gravity.END
            }

        }
    }

    val sexArr = arrayListOf<String>("", "男", "女")
    val guojiArr = arrayListOf<String>("", "大陆", "香港", "澳门", "台湾")
    val styleArr = arrayListOf<String>("", "身份证", "护照")

    /**
     * 类型
     */
    var chooseStyle = ""
    var chooseCountry = ""
    var chooseSex = ""

    private fun initSexSpinner() {
        sexSpinner.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, sexArr)
        sexSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {
            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                chooseSex = sexArr[p2]
                (p1 as TextView).textSize = 14f
                (p1 as TextView).gravity = Gravity.END
            }

        }
    }


    private fun save() {
        val realName = etRealName.text.toString()
        val cardNumber = etIdCardNumber.text.toString()
        val time = tvChooseCardTime.text.toString()
        when {
            realName == "" -> showToastShort("请输入姓名")
            cardNumber == "" -> showToastShort("请输入身份证号码")
            time == "" -> showToastShort("请选择有效期时间")
            else -> {
                val userInfo = ProUserInfo()
                userInfo.gender = when (chooseSex) {
                    "男" -> "1"
                    "女" -> "2"
                    else -> "0"
                }
                userInfo.country = chooseCountry

                userInfo.cardType = when (chooseStyle) {
                    "身份证" -> "1"
                    "护照" -> "2"
                    else -> "0"
                }

                userInfo.cardNo = cardNumber
                userInfo.realName = realName
                userInfo.cardPeriod = time
                userInfo.lng = location!!.longitude.toString()
                userInfo.lat = location!!.latitude.toString()
                userInfo.address = addressStr
                send!!.updateUserInfo(userInfo, handler!!)

            }

        }


    }
}